package org.mspring.mlog.service;

import org.mspring.mlog.dao.ConfigDao;
import org.mspring.mlog.entity.Config;
import org.mspring.nbee.orm.dao.sql.builder.part.condition.SqlCondition;
import org.mspring.nbee.orm.dao.sql.pager.PageResult;
import org.mspring.nbee.orm.dao.sql.pager.Pager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Gao Youbo
 * @since 2015-01-03 18:08:20
 */
@Service
public class ConfigService {

    private static final Logger log = LoggerFactory.getLogger(ConfigService.class);

    private ConfigDao configDao;

    public Config findById(long id) {
        return configDao.findById(id);
    }

    /**
     * 根据分组和名称查找
     *
     * @param groupName
     * @param name
     * @return
     */
    public Config findByName(String groupName, String name) {
        return configDao.findByName(groupName, name);
    }

    /**
     * 加载所有
     *
     * @return
     */
    public List<Config> listAll() {
        return configDao.listAll();
    }

    public PageResult<Config> list(List<SqlCondition> conditions, Pager pager) {
        return configDao.listPage(conditions, pager);
    }


    @Transactional
    public void insertOrUpdateConfigs(List<Config> configs) {
        for (Config config : configs) {
            Config temp = findByName(config.getGroupName(), config.getName());
            if (temp != null) {
                config.setId(temp.getId());
            }
            insertOrUpdate(config);
        }
    }

    @Transactional
    public boolean insertOrUpdate(Config config) {
        if (config.getId() == null || config.getId() <= 0) {
            return configDao.insert(config);
        } else {
            return configDao.update(config);
        }
    }

    @Transactional
    public boolean insert(Config config) {
        return configDao.insert(config);
    }

    @Transactional
    public boolean update(Config config) {
        return configDao.update(config);
    }

    @Transactional
    public boolean deleteById(long id) {
        return configDao.deleteById(id);
    }

    @Autowired
    public void setConfigDao(ConfigDao configDao) {
        this.configDao = configDao;
    }

}